package com.cloud.jmmTest;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
// 永不终止的循环 - 可见性问题
public class LoopTest {
    static boolean stop = false; //停止标记

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stop = true; // volatile 的写
        });
        System.out.println("start " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        t.start();
        foo();
    }

    private static void foo() {
        while (true) {
            boolean b = stop; // volatile 的读
            if (b) {
                break;
            }
        }
        System.out.println("end " + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
    }
}
